package com.wcs.spring.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import com.wcs.spring.util.Const;

/**
 * <p>
 * Title: Phicomm_[子系统统名]_[模块名]
 * </p>
 * <p>
 * Description: [描述该类概要功能介绍]
 * </p>
 * 
 * @author zyl
 * @version $Revision$ 2014-9-17
 * @author (lastest modification by $Author$)
 * @since 1.0
 */
public class SessionFilter extends OncePerRequestFilter {

	Logger logger = LoggerFactory.getLogger(SessionFilter.class);

	/**
	 * @see org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
		try {
			this.filler(request, response, filterChain);
		}
		catch (Exception e) {
			e.printStackTrace();
			// logger.error("SessionFilter exception", e);
		}

	}

	/**
	 * <p>
	 * Discription:[拦截器]
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @param filterChain
	 * @throws ServletException
	 * @throws IOException
	 */
	private void filler(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String uri = request.getRequestURI();
		String strarray = "";
		Object obj = null;
		boolean doFilter = true;
		if ("/".equals(uri) || uri.endsWith("/mgt/") || uri.endsWith("/mgt")) {
			doFilter = false;
		}
		else {
			if (uri.indexOf("/mgt/") != -1) {
				strarray = "login.do,toLogin.do,logout.do,toSchoolSimple.do";
				obj = request.getSession().getAttribute(Const.SESSION_SYS_USER);
			}
			else if (uri.indexOf("/ph/") != -1) {
				strarray = "login.do,toLogin.do,logout.do";
				obj = request.getSession().getAttribute(Const.SESSION_PH_USER);
			}

			String[] noFilters = strarray.split(",");

			// uri中包含background时才进行过滤
			// 是否过滤
			for (String s : noFilters) {
				if (uri.indexOf(s) != -1) {
					// 如果uri中包含不过滤的uri，则不进行过滤
					doFilter = false;
					break;
				}
			}
		}

		if (doFilter) {
			// 执行过滤
			// 从session中获取登录者实体
			if (null == obj) {
				if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))
						|| request.getParameter("ajax") != null) {
					String type = "ph";
					PrintWriter out = response.getWriter();
					if (uri.indexOf("/mgt/") != -1) {
						type = "mgt";
					}

					out.println("{\"statusCode\":\"301\",\"type\":\"" + type + "\"}");
				}
				else {

					String basepath = request.getContextPath();
					String str = java.net.URLEncoder.encode("网页过期，请重新登录！", "UTF-8");
					// String str = "网页过期，请重新登录！";
					request.setCharacterEncoding("UTF-8");
					response.setCharacterEncoding("UTF-8");
					PrintWriter out = response.getWriter();
					StringBuilder builder = new StringBuilder();
					builder.append("<script type=\"text/javascript\">");
					builder.append("alert(decodeURI('");
					builder.append(str);
					builder.append("')); window.top.location.href='");
					builder.append(basepath);
					if (uri.indexOf("/mgt/") != -1) {
						builder.append("/mgt/sys/toLogin.do");
					}
					else if (uri.indexOf("/ph/") != -1) {
						builder.append("/ph/sys/toLogin.do");
					}
					builder.append("';");
					builder.append("</script>");
					out.print(builder.toString());
				}
			}
			else {
				filterChain.doFilter(request, response);
			}
		}
		else {
			filterChain.doFilter(request, response);
		}
	}

}
